package com.dingreading.cloud.subject.service.impl;

import com.dingreading.cloud.subject.entity.CourseTypes;
import com.dingreading.cloud.subject.entity.table.CourseTypesTableDef;
import com.dingreading.cloud.subject.mapper.CourseTypesMapper;
import com.dingreading.cloud.subject.service.CourseTypesService;
import com.mybatisflex.core.query.QueryCondition;
import com.mybatisflex.core.query.QueryWrapper;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 服务层实现。
 *
 * @author Administrator
 * @since 2023-11-22
 */
@Service
public class CourseTypesServiceImpl extends BaseServiceImpl<CourseTypesMapper, CourseTypes, CourseTypesTableDef> implements CourseTypesService {

    @Override
    protected CourseTypesTableDef getTable() {
        return CourseTypesTableDef.courseTypes;
    }


    @Override
    public List<CourseTypes> getMainCourseTypesV3(List<Long> subjectIdList) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.parentId.eq(0L))
                .and(table.enabled.eq(1));
        if (CollectionUtils.isNotEmpty(subjectIdList)) {
            condition.and(table.subjectType.eq("").or(getSubjectTypeSql(subjectIdList)));
        }

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.showOrder.asc());

        return getMapper().selectListByQuery(wrapper);
    }

    @Override
    public List<CourseTypes> getChildCourseTypesV3(Long mainId, List<Long> subjectIdList) {
        QueryCondition condition = QueryCondition.createEmpty();
        condition.and(table.parentId.ne(0L))
                .and(table.mainId.eq(mainId))
                .and(table.enabled.eq(1));
        if (CollectionUtils.isNotEmpty(subjectIdList)) {
            condition.and(table.subjectType.eq("").or(getSubjectTypeSql(subjectIdList)));
        }

        QueryWrapper wrapper = QueryWrapper.create()
                .where(condition)
                .orderBy(table.levelIndex.asc(), table.showOrder.asc());

        return getMapper().selectListByQuery(wrapper);
    }

    @Override
    public List<CourseTypes> getMainCourseTypesById(List<Long> courseIdList) {
        QueryCondition condition = QueryCondition.createEmpty()
                .and(table.parentId.eq(0L))
                .and(table.id.in(courseIdList));
        return getMapper().selectListByCondition(condition);
    }

    public static String getSubjectTypeSql(List<Long> subjectIdList) {
        String sql = subjectIdList.stream().map(String::valueOf).collect(Collectors.joining("|"));
        return "subject_type REGEXP '(^|,)(" + sql + ")(,|$)'";
    }

}
